<?php


namespace Frieza\Modules\RiskContent\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Doraemon\module\ContentChecking\Common\CheckLogConst;
use Doraemon\module\ContentChecking\Common\QueryCommand;
use Doraemon\module\ContentChecking\Service\CheckLog;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Frieza\Modules\RiskContent\Actions\Approved;
use Frieza\Modules\RiskContent\Actions\SetDefault4Avatar;
use Frieza\Modules\RiskContent\Actions\SetDefault4Background;
use Frieza\Modules\RiskContent\Actions\SetDefault4Nick;
use Frieza\Modules\RiskContent\Actions\SetPrevious4nick;
use Frieza\Modules\RiskContent\Actions\SetVisibleYourself;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Doraemon\service\Member as sMember;
use Doraemon\service\User;

class CheckLogController extends Controller
{

    const PAGE_SIZE = 20;


    /**
     * @param Request $request
     * @param Content $content
     * @return Content
     * @throws \Exception
     */
    public function list(Request $request, Content $content): Content
    {

        $command = $this->_request2Command($request,CheckLogConst::SCENES_AVATAR);


        $infos = (new CheckLog())->screen($command);

        if(!empty($infos['list'])){
            foreach($infos['list'] as &$val){

                $val['expand'] = $this->_getRemarksExpand4Img($val['remarksExpand'],$val['uid'],CheckLogConst::SCENES_AVATAR);
            }
        }

        $gridModel = new GridDataModel($infos['list'], $infos['total'], ['perPage' => $infos['pageSize']]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {

            $this->_filter($grid);

            $grid->column('avatar', '头像')->display(function () {
                $userInfo = sMember::getUserInfoByUid($this->uid);

                $avatarPicUrl = User::getUserAvatarPicUrl($this->uid, $userInfo["avatar_version"]);

                return '<img src = "' . $avatarPicUrl[0] . '"width = 45px heigh = 45px/>';
            });

            $grid->column('nick', '昵称')->display(function () {
                $userInfo = sMember::getUserInfoByUid($this->uid);

                return "<a href='/admin/user/Detail/$this->uid' target='_blank' >" . $userInfo['nick'] . "</a>";
            })->width(200);
            $grid->column('uid', '用户id');

            $grid->column('is_risk', '风险项')->display(function(){
                if($this->is_risk == 1){
                    return '<img src="https://img.haohaozhu.cn/Op-imageShow/cf6a8300g00g0Gk00r951q1?iv=1">';
                }else{
                    return "";
                }
            });
            //人工审核通过或者无违规，不展示备注。
            $grid->column('remarks', '备注')->display(function (){
                if(empty($this->remarksExpand)){
                    $_text= '';
                }else{
                    $_text= '该用户修改多次，且包含疑似违规记录';
                }

                //人工审核通过或者无违规，不展示备注。
                if($this->conclusion_type == CheckLogConst::CONCLUSION_TYPE_YES
                    || $this->status == CheckLogConst::MANUAL_REVIEW_PASSED){

                    return $_text;
                }else{
                    $remarks = json_decode($this->remarks,true);
                    $avatarPicUrl = User::getUserAvatarPicUrl($this->uid,$remarks['avatarVersion']);
                    $html =  '<img src = "' . $avatarPicUrl[0] . '"width = 45px heigh = 45px/>&nbsp;&nbsp;违规原因：';
                    $remarks['seasons'] = $remarks['seasons'] && is_array($remarks['seasons']) ? implode('，',$remarks['seasons']) : $remarks['seasons'];
                    $html .= $remarks['seasons'];

                    if(!empty($remarks['other_seasons'])) {
                        $html .= "，" . $remarks['other_seasons'];
                    }

                    return $html . "<br/>" . $_text;
                }

            })->expand(function () {
                return $this->expand;
            });
            $grid->column('addtime', '更改时间');

            $grid->setActionClass(DropdownActions::class);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();

                //$actions->append('<a href=""><i class="fa fa-eye"></i></a>');

                if(in_array($actions->row->status,[CheckLogConst::OWNED_REVIEW_FAILED,CheckLogConst::THIRD_PARTY_REVIEW_FAILED])){
                    $actions->add(new Approved);
                }
                $actions->add(new SetDefault4Avatar);

            });

        });

        Admin::script($this->imgScript());
        $tab = new \Encore\Admin\Widgets\Tab();
        $tab->add('头像审核列表', $listGrid->render());
        $tab->addLink('背景图审核列表', 'backgroundList');
        $tab->addLink('私信图审核列表', url('admin/im/imgCheckList'));
        $tab->addLink('昵称审核列表', 'nickList');
        $tab->addLink('简介审核列表', 'profileList');
        $content->row($tab);
        return $content->header('用户基础信息审核')->breadcrumb(['text' => '用户基础信息审核']);

    }


    public function backgroundList(Request $request, Content $content): Content
    {

        $command = $this->_request2Command($request,CheckLogConst::SCENES_BACKGROUND_MAP);

        $infos = (new CheckLog())->screen($command);

        if(!empty($infos['list'])){
            foreach($infos['list'] as &$val){
                $val['expand'] = $this->_getRemarksExpand4Img($val['remarksExpand'],'',CheckLogConst::SCENES_BACKGROUND_MAP);
            }
        }

        $gridModel = new GridDataModel($infos['list'], $infos['total'], ['perPage' => $infos['pageSize']]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {


            $this->_filter($grid);
            $grid->column('avatar', '头像')->display(function () {
                $userInfo = sMember::getUserInfoByUid($this->uid);

                $avatarPicUrl = User::getUserAvatarPicUrl($this->uid, $userInfo["avatar_version"]);

                return '<img src = "' . $avatarPicUrl[0] . '"width = 45px heigh = 45px/>';
            });

            $grid->column('nick', '昵称')->display(function () {
                $userInfo = sMember::getUserInfoByUid($this->uid);

                return "<a href='/admin/user/Detail/$this->uid' target='_blank' >" . $userInfo['nick'] . "</a>";
            })->width(200);

            $grid->column('uid', '用户id');
            $grid->column('is_risk', '风险项')->display(function(){
                if($this->is_risk == 1){
                    return '<img src="https://img.haohaozhu.cn/Op-imageShow/cf6a8300g00g0Gk00r951q1?iv=1">';
                }else{
                    return "";
                }
            });
            $grid->column('remarks', '备注')->display(function (){
                if(empty($this->remarksExpand)){
                    $_text= '';
                }else{
                    $_text= '该用户修改多次，且包含疑似违规记录';
                }

                //人工审核通过或者无违规，不展示备注。
                if($this->conclusion_type == CheckLogConst::CONCLUSION_TYPE_YES
                    || $this->status == CheckLogConst::MANUAL_REVIEW_PASSED){

                    return $_text;
                }else {
                    $remarks = json_decode($this->remarks,true);
                    $html =  '<img src = "' . $remarks['imgUrl'] . '"width = 45px heigh = 45px/>&nbsp;&nbsp;违规原因：';

                    $remarks['seasons'] = $remarks['seasons'] && is_array($remarks['seasons']) ? implode('，',$remarks['seasons']) : $remarks['seasons'];
                    $html .= $remarks['seasons'];

                    if(!empty($remarks['other_seasons'])) {
                        $html .= "，" . $remarks['other_seasons'];
                    }

                    return $html . "</br>" . $_text;
                }

            })->expand(function () {
                return $this->expand;
            });
            $grid->column('addtime', '更改时间');


            $grid->setActionClass(DropdownActions::class);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();

                if(in_array($actions->row->status,[CheckLogConst::OWNED_REVIEW_FAILED,CheckLogConst::THIRD_PARTY_REVIEW_FAILED])) {

                    $actions->add(new Approved);
                }
                $actions->add(new SetDefault4Background);

            });

        });


        $tab = new \Encore\Admin\Widgets\Tab();
        $tab->addLink('头像审核列表', 'list');
        $tab->add('背景图审核列表', $listGrid->render(),true);
        $tab->addLink('私信图审核列表', url('admin/im/imgCheckList'));
        $tab->addLink('昵称审核列表', 'nickList');
        $tab->addLink('简介审核列表', 'profileList');
        $content->row($tab);
        return $content->header('用户基础信息审核')->breadcrumb(['text' => '用户基础信息审核']);

    }


    public function nickList(Request $request, Content $content): Content
    {


        $command = $this->_request2Command($request,CheckLogConst::SCENES_NICKNAME);


        $infos = (new CheckLog())->screen($command);


        $gridModel = new GridDataModel($infos['list'], $infos['total'], ['perPage' => $infos['pageSize']]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {

            $this->_filter($grid);
            $grid->column('avatar', '头像')->display(function () {
                $userInfo = sMember::getUserInfoByUid($this->uid);

                $avatarPicUrl = User::getUserAvatarPicUrl($this->uid, $userInfo["avatar_version"]);

                return '<img src = "' . $avatarPicUrl[0] . '"width = 45px heigh = 45px/>';
            });

            $grid->column('nick', '昵称')->display(function () {
                $userInfo = sMember::getUserInfoByUid($this->uid);

                return "<a href='/admin/user/Detail/$this->uid' target='_blank' >" . $userInfo['nick'] . "</a>";
            })->width(200);
            $grid->column('uid', '用户id');

            $grid->column('is_risk', '风险项')->display(function(){
                if($this->is_risk == 1){
                    $text = $this->status == CheckLogConst::THIRD_PARTY_REVIEW_FAILED ? "(第三方)" : '(系统）';
                    return '<img src="https://img.haohaozhu.cn/Op-imageShow/cf6a8300g00g0Gk00r951q1?iv=1">' . $text;
                }else{
                    return "";
                }
            });

            $grid->column('remarks', '备注')->display(function (){
                //人工审核通过或者无违规，不展示备注。
                if($this->conclusion_type == CheckLogConst::CONCLUSION_TYPE_YES
                    || $this->status == CheckLogConst::MANUAL_REVIEW_PASSED){
                    return '';
                }else{
                    $remarks = json_decode($this->remarks,true);

                    $html = "违规昵称：" . $remarks['nick'] . "，";
                    $remarks['seasons'] = is_array($remarks['seasons']) ? implode(',',$remarks['seasons']) : $remarks['seasons'];

                    $html .= "违规原因：" . $remarks['seasons'];

                    if(!empty($remarks['other_seasons'])) {
                        $html .= "，" . $remarks['other_seasons'];
                    }

                    return $html;
                }
            });

            $grid->column('addtime', '更改时间');


            $grid->setActionClass(DropdownActions::class);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();

                $actions->append('<a href=""><i class="fa fa-eye"></i></a>');
                if(in_array($actions->row->status,[CheckLogConst::OWNED_REVIEW_FAILED,CheckLogConst::THIRD_PARTY_REVIEW_FAILED])){
                    $actions->add(new Approved);
                }
                $actions->add(new SetPrevious4nick);

            });

        });


        $tab = new \Encore\Admin\Widgets\Tab();

        $tab->addLink('头像审核列表', 'list');
        $tab->addLink('背景图审核列表', 'backgroundList');
        $tab->addLink('私信图审核列表', url('admin/im/imgCheckList'));
        $tab->add('昵称审核列表', $listGrid->render(),true);
        $tab->addLink('简介审核列表', 'profileList');
        $content->row($tab);
        return $content->header('用户基础信息审核')->breadcrumb(['text' => '用户基础信息审核'])->row("<div style='display:none;position:fixed;z-index:100;top:50px;left:100%;width:600px;height:600px;' class='imgMoveDiv' id='remarksExpand'></div>");

    }

    public function profileList(Request $request, Content $content): Content
    {


        $command = $this->_request2Command($request,CheckLogConst::SCENES_PROFILE);


        $infos = (new CheckLog())->screen($command);


        if(!empty($infos['list'])){
            foreach($infos['list'] as &$val){

                $val['expand'] = $this->_getRemarksExpand($val['remarksExpand'],CheckLogConst::SCENES_PROFILE);
            }
        }

        $gridModel = new GridDataModel($infos['list'], $infos['total'], ['perPage' => $infos['pageSize']]);


        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $this->_filter($grid);
            $grid->column('avatar', '头像')->display(function () {
                $userInfo = sMember::getUserInfoByUid($this->uid);

                $avatarPicUrl = User::getUserAvatarPicUrl($this->uid, $userInfo["avatar_version"]);

                return '<img src = "' . $avatarPicUrl[0] . '"width = 45px heigh = 45px/>';
            });

            $grid->column('nick', '昵称')->display(function () {
                $userInfo = sMember::getUserInfoByUid($this->uid);

                return "<a href='/admin/user/Detail/$this->uid' target='_blank' >" . $userInfo['nick'] . "</a>";
            })->width(200);
            $grid->column('uid', '用户id');

            $grid->column('is_risk', '风险项')->display(function(){
                if($this->is_risk == 1){
                    $text = $this->status == CheckLogConst::THIRD_PARTY_REVIEW_FAILED ? "(第三方)" : '(系统）';
                    return '<img src="https://img.haohaozhu.cn/Op-imageShow/cf6a8300g00g0Gk00r951q1?iv=1">' . $text;
                }else{
                    return "";
                }
            });
            $grid->column('remarks', '备注')->display(function (){

                if(empty($this->remarksExpand)){
                    $_text= '';
                }else{
                    $_text= '该用户修改多次，且包含疑似违规记录';
                }

                //人工审核通过或者无违规，不展示备注。
                if($this->conclusion_type == CheckLogConst::CONCLUSION_TYPE_YES
                    || $this->status == CheckLogConst::MANUAL_REVIEW_PASSED){

                    return $_text;
                }else{
                    $remarks = json_decode($this->remarks, true);

                    $html = "违规简介：" . $remarks['profile'] . "，";

                    $remarks['seasons'] = is_array($remarks['seasons']) ? implode(',', $remarks['seasons']) : $remarks['seasons'];

                    $html .= "违规原因：" . $remarks['seasons'] ;

                    if(!empty($remarks['other_seasons'])) {
                        $html .= "，" . $remarks['other_seasons'];
                    }

                    return $html .  "<br>" . $_text;
                }

            })->expand(function () {
                return $this->expand;
            });
            $grid->column('addtime', '更改时间');


            $grid->setActionClass(DropdownActions::class);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();

                $actions->append('<a href=""><i class="fa fa-eye"></i></a>');

                if(in_array($actions->row->status,[CheckLogConst::OWNED_REVIEW_FAILED,CheckLogConst::THIRD_PARTY_REVIEW_FAILED])) {
                    $actions->add(new Approved);
                }
                $actions->add(new SetVisibleYourself);
            });

        });



        $tab = new \Encore\Admin\Widgets\Tab();
        $tab->addLink('头像审核列表', 'list');
        $tab->addLink('背景图审核列表', 'backgroundList');
        $tab->addLink('私信图审核列表', url('admin/im/imgCheckList'));
        $tab->addLink('昵称审核列表', 'nickList');
        $tab->add('简介审核列表', $listGrid->render(),true);
        $content->row($tab);
        return $content->header('用户基础信息审核')->breadcrumb(['text' => '用户基础信息审核'])
            ->row("<div style='display:none;position:fixed;z-index:100;top:50px;left:100%;width:600px;height:600px;' class='imgMoveDiv' id='remarksExpand'></div>");

    }



    /**
     * @param Grid $grid
     * @return void
     */
    private function _filter(Grid &$grid){
        $grid->disableCreateButton();
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableColumnSelector();
        $grid->expandFilter();

        $grid->filter(function (Grid\Filter $filter) {

            $filter->disableIdFilter();

            $filter->column(8, function ($filter) {

                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('uid', '用户ID');
                });
                $filter->column(1 / 2, function (\Encore\Admin\Grid\Filter $filter) {

                    $filter->dropDown('addtime', [
                        'addtime' => '更改时间'
                    ])->betweenDatetime();
                });
            });

            $filter->column(8, function ($filter) {

                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('isRisk', '风险项')->checkbox([1 => "是"]);
                });


            });


            $filter->expend();
        });
    }


    /**
     * @param Request $request
     * @param integer $scenes
     * @return QueryCommand
     */
    private function _request2Command(Request $request,int $scenes = 0): QueryCommand
    {

        $command = new QueryCommand();

        /**
         * 这里做不涉及业务的，基本检查。
         */
        $command->page = $request->input("page", 1);
        if ($command->page < 1) {
            $command->page = 1;
        }

        $command->pageSize = $request->input("per_page", 20);
        if ($command->pageSize < 0) {
            $command->pageSize = 20;
        }

        if(empty($scenes)){
            $command->scenes = $request->input("scenes", 1);
        }else{
            $command->scenes = $scenes;
        }

        $command->uid = (int)$request->input("uid", 0);

        $command->addTimeStart = $request->input("addtime", [])['start'] ?? '';
        $command->addTimeEnd = $request->input("addtime", [])['end'] ?? '';

        $command->isRisk = (int)$request->input("isRisk", 0);

        return $command;
    }

    public function imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv111').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv111').click(function() {
                $('.imgMoveDiv').hide();      
            });
SCRIPT;
    }

    private function _getRemarksExpand4Img($remarksExpand,$uid,$scenes): string
    {
        $row = new Row();

        $row->column(12, implode("", array_map(function ($remarks)use($uid,$scenes) {

            $remarks = json_decode($remarks,true);

            if($scenes == CheckLogConst::SCENES_AVATAR){

                $avatarPicUrl = User::getUserAvatarPicUrl($uid,$remarks['avatarVersion']);
                $html =  '<img src = "' . $avatarPicUrl[0] . '"width = 45px heigh = 45px/>&nbsp;&nbsp;违规原因：';
            }else if($scenes == CheckLogConst::SCENES_BACKGROUND_MAP){

                $html =  '<img src = "' . $remarks['imgUrl'] . '"width = 45px heigh = 45px/>&nbsp;&nbsp;违规原因：';
            }

            $remarks['seasons'] = $remarks['seasons'] && is_array($remarks['seasons']) ? implode('，',$remarks['seasons']) : $remarks['seasons'];
            $html .= $remarks['seasons']. '，' . $remarks['other_seasons'] . "<br/>";

            return "-" . $html;
        }, (array)$remarksExpand)));
        return $row->render();
    }

    private function _getRemarksExpand4Text($remarksExpand): string
    {

        $row = new Row();
        $row->column(12, implode("", array_map(function ($remarks) {

            $remarks = json_decode($remarks,true);
            $html = '';

            "$remarks<br/>";
        }, (array)$remarksExpand)));
        return $row->render();
    }

    private function _getRemarksExpand($remarksExpand,$scenes): string
    {

        $row = new Row();
        $row->column(12, implode("", array_map(function ($remarks)use($scenes) {

            $remarks = json_decode($remarks,true);

            $html = '';
            if($scenes == CheckLogConst::SCENES_NICKNAME){
                $html = "违规昵称：" . $remarks['nick'] . "，";
            }else if($scenes == CheckLogConst::SCENES_PROFILE){
                $html = "违规个人简介：" . $remarks['profile'] . "，";
            }

            $html .= "违规原因：" . $remarks['seasons'];

            return "-$html<br/>";
        }, (array)$remarksExpand)));
        return $row->render();
    }
}